<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/1/3/003
 * Time: 14:13
 */

require_once  "./Baocms/Lib/Action/Api/WX/Wx.Config.php";
class JSSDK
{
    public $appId;
    public $appSecret;
    public $nonceStr;
    public $timeStamp;
    public $webUrl;
    public $token_file = './Baocms/Lib/Action/Api/WX/JSSDK/token.txt';
    public $signature_file = './Baocms/Lib/Action/Api/WX/JSSDK/signature.txt';

    public function __construct()
    {
        $this->appId = WxConfig::APPID;
        $this->appSecret = WxConfig::APPSECRET;
        $this->nonceStr = $this->nonceStr();
        $this->timeStamp = time();
        //$this->webUrl = 'http://www.freqb.com/mobilenew/fujin/index.html';

    }

    //获取access_token并保存到token.txt文件中
    public function build_access_token()
    {
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $this->appId . "&secret="
            . $this->appSecret;
        $ch = curl_init(); //初始化一个CURL对象
        curl_setopt($ch, CURLOPT_URL, $url);//设置你所需要抓取的URL
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); //不验证证书
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//设置curl参数，要求结果是否输出到屏幕上，为true的时候是不返回到网页中,假设上面的0换成1的话，那么接下来的$data就需要echo一下。
        $data = json_decode(curl_exec($ch));
        curl_close($ch);
        if ($data->access_token) {
            $token_file = fopen($this->token_file, "w") or die("Unable to open file!");//打开token.txt文件，没有会新建
            $expires_in = intval($data->expires_in) + time();
            $re = json_encode(array('access_token' => $data->access_token, 'expires_in' => $expires_in));
            fwrite($token_file, $re);//重写tken.txt全部内容
            fclose($token_file);//关闭文件流
            return $data->access_token;
        } else {
            return $data->errmsg;
        }
    }

    //读取token
    public function read_token()
    {
        $token_file = fopen($this->token_file, "r") or die("Unable to open file!");
        $rs = fgets($token_file);
        fclose($token_file);
        $rs = json_decode($rs);
        if (isset($rs->expires_in) && $rs->expires_in > time() && $rs->access_token != null) {
            return $rs->access_token;
        } else {
            return $access_token = $this->build_access_token();
        }
    }

    //获取ticket并保存到ticket.txt文件中
    public function get_ticket()
    {
        $access_token = $this->read_token();
        $url = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=' . $access_token . '&type=jsapi';
        $ch = curl_init(); //初始化一个CURL对象
        curl_setopt($ch, CURLOPT_URL, $url);//设置你所需要抓取的URL
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); //不验证证书
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//设置curl参数，要求结果是否输出到屏幕上，为true的时候是不返回到网页中,假设上面的0换成1的话，那么接下来的$data就需要echo一下。
        $data = json_decode(curl_exec($ch));
        curl_close($ch);
        $ticket_file = fopen($this->signature_file, "w") or die("Unable to open file!");//打开token.txt文件，没有会新建
        $re = json_encode(array('ticket' => $data->ticket, 'expires_in' => intval($data->expires_in) + time()));
        fwrite($ticket_file, $re);//重写tken.txt全部内容
        fclose($ticket_file);//关闭文件流
        return $data->ticket;

    }

    //读取ticket
    public function read_ticket()
    {
        $ticket_file = fopen($this->signature_file, "r") or die("Unable to open file!");
        $rs = fgets($ticket_file);
        fclose($ticket_file);
        $rs = json_decode($rs);
        if (isset($rs->expires_in) && $rs->expires_in > time() && $rs->ticket != null) {
            return $rs->ticket;
        } else {
            return $ticket = $this->get_ticket();
        }
    }

    public function get_signature()
    {
        $ticket = $this->read_ticket();
        $nonceStr = $this->nonceStr;
        $timeStamp = $this->timeStamp;
        $url = $this->webUrl;
        $str = "jsapi_ticket=".$ticket."&noncestr=".$nonceStr."&timestamp=".$timeStamp."&url=".$url;
        $signature = sha1($str);
        $result = array('signature' => $signature, 'nonceStr' => $nonceStr, 'timeStamp' => $timeStamp, 'appId' => $this->appId);
        return $result;
    }

    public function nonceStr()
    {

        $str = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        $key = "";
        for ($i = 0; $i < 16; $i++) {
            $key .= $str{mt_rand(0, 61)};    //生成php随机数
        }
        return $key;
    }

    public function wechat_jssdk($webUrl,$debug=false,$jssdkType=false)
    {
        $this->webUrl = $webUrl;
        $res = $this->get_signature();
//        var_dump($res);
        $api = array(
            'checkJsApi',
            'onMenuShareTimeline',
            'onMenuShareAppMessage',
            'onMenuShareQQ',
            'onMenuShareWeibo',
            'hideMenuItems',
            'showMenuItems',
            'hideAllNonBaseMenuItem',
            'showAllNonBaseMenuItem',
            'translateVoice',
            'startRecord',
            'stopRecord',
            'onRecordEnd',
            'playVoice',
            'pauseVoice',
            'stopVoice',
            'uploadVoice',
            'downloadVoice',
            'chooseImage',
            'previewImage',
            'uploadImage',
            'downloadImage',
            'getNetworkType',
            'openLocation',
            'getLocation',
            'hideOptionMenu',
            'showOptionMenu',
            'closeWindow',
            'scanQRCode',
            'chooseWXPay',
            'openProductSpecificView',
            'addCard',
            'chooseCard',
            'openCard'
        );
        $config = array(
            'debug' => $debug,
            'appId' => $res['appId'],
            'timestamp' => $res['timeStamp'],
            'nonceStr' => $res['nonceStr'],
            'signature' => $res['signature'],
            'jsApiList' => $api
        );
        $config = json_encode($config);

        //var_dump($config);die;

        $script_text = <<<EOF
<script src="http://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>
<script type="text/javascript">
wx.config({$config});
</script>
EOF;
        if ($jssdkType==false){
            return $script_text;
        }else{
            return $config;
        }
    }
}
